package org.academic.texteditor.gui.plugin.document;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JToolBar;

import org.academic.texteditor.gui.PrincipalWindow;
import org.academic.texteditor.gui.component.PageContainer;
import org.academic.texteditor.gui.component.menu.MenuFactory;
import org.academic.texteditor.gui.component.toolbar.ToolBarFactory;
import org.academic.texteditor.gui.form.PageContainerForm;
import org.academic.texteditor.gui.plugin.BasePlugin;

public class OpenDocumentPlugin extends BasePlugin {

	private static final long serialVersionUID = 7599132008526800360L;
	
	public OpenDocumentPlugin() {
		super("openDocumentPlugin");
	}

	@Override
	public void initialize(PageContainer pageContainer) {
		JMenu menu = MenuFactory.getApplication();
		MenuFactory.createMenuItem(menu, 1, "open", "menu.application.open", this);
		menu.setVisible(true);
		
		JToolBar main = ToolBarFactory.getMain();
		ToolBarFactory.createButton(main, "open", 1, "toolbar.main.open", "images/open-icon.png", this);
	}
	
	@Override
	public void activate() {
		
	}

	@Override
	public void execute() {
		JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
		int returnVal = fileChooser.showOpenDialog(PrincipalWindow.getInstance());
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			
			try {
				FileReader reader = new FileReader(file);
				
				PageContainerForm form = new PageContainerForm();
				PageContainer pageContainer = form.getPageContainer();
				pageContainer.openDocument(reader);
				
				PrincipalWindow.getInstance().openWindow(form);
				
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void deactivate() {

	}

	@Override
	public void destroy() {
		JMenu menu = MenuFactory.getApplication();
		MenuFactory.removeMenuItem(menu, "open");
		
		JToolBar main = ToolBarFactory.getMain();
		ToolBarFactory.removeButton(main, "open");
	}

}
